//建立文件applycation的数据集
const applycationType = {
  txt: "text/plain",
  doc: "application/msword",
  docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  pdf: "application/pdf",
  xls: "application/vnd.ms-excel",
  xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  xlsm: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  xlm: "application/vnd.ms-excel",
  ppt: "application/vnd.ms-powerpoint",
  pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
  wps: "application/vnd.ms-works",
  tgz: "application/x-compressed",
  tar: "application/x-tar",
  zip: "application/zip",
  bmp: "image/bmp",
  gif: "image/gif",
  jpe: "image/jpeg",
  jpeg: "image/jpeg"
};

export default function (filename, res) {
  //filename  test.txt
  //res   后台传递的文件流

  if (!filename) return;
  //根据文件名获取文件格式
  let fileType = filename.split(".").pop();
  //获取该文件的application
  let fileApplycation = applycationType[fileType];
  //获取时间戳
  let timestap = new Date().getTime();

  try {
    let data = new Blob([res], { type: fileApplycation });
    let blobUrl = window.URL.createObjectURL(data);
    let a = document.createElement("a");
    a.style.display = "none";
    //重命名文件=时间戳+原文件名
    a.download = timestap + filename;
    a.href = blobUrl;
    a.click();
  } catch (e) {
    alert("下载文件出错");
  }
}
